package com.cn.codebrush.链表;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author Boolean
 * @Date 2022/5/24 17:11
 * @Version 1.0
 */
public class No23合并K个升序链表 {
    public static void main(String[] args) {

    }


    /**
     * 分治法
     * @param lists
     * @return
     */
    public ListNode mergeKLists2(ListNode[] lists) {
        return merge(lists, 0, lists.length - 1);
    }

    public ListNode merge(ListNode[] lists, int l, int r) {
        if (l == r) {
            return lists[l];
        }
        if (l > r) {
            return null;
        }
        int mid = (l + r) >> 1;
        return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));
    }

    public ListNode mergeTwoLists(ListNode a, ListNode b) {
        if (a == null || b == null) {
            return a != null ? a : b;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head, aPtr = a, bPtr = b;
        while (aPtr != null && bPtr != null) {
            if (aPtr.val < bPtr.val) {
                tail.next = aPtr;
                aPtr = aPtr.next;
            } else {
                tail.next = bPtr;
                bPtr = bPtr.next;
            }
            tail = tail.next;
        }
        tail.next = (aPtr != null ? aPtr : bPtr);
        return head.next;
    }




    /**
     * 暴力求解
     * @param lists
     * @return
     */
    public ListNode mergeKLists(ListNode[] lists) {

        int k = lists.length;
        List<Integer> list = new ArrayList<Integer>();
        for(int i=0;i<k;i++){
            ListNode node = lists[i];
            ListNode temp = node;
            while(temp != null){
                list.add(temp.val);
                temp = temp.next;
            }
        }

        Collections.sort(list);
        ListNode resNode = new ListNode();
        ListNode tempNode = resNode;
        for(int j=0;j<list.size();j++){
            tempNode.next = new ListNode(list.get(j));
            tempNode = tempNode.next;
        }

        return resNode.next;
    }
}
